package com.zhangck.bos2_0.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhangck.bos2_0.Service.system.PermissionServices;
import com.zhangck.bos2_0.Service.system.RoleServices;
import com.zhangck.bos2_0.Service.system.UserServices;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;

/** 
* @author 上午茶
* @version 创建时间：2018年6月16日 下午6:32:40 
* 类说明 
*/
/*@Service("bosRealm")*/
public class BosRealm extends AuthorizingRealm {

	@Autowired
	private UserServices userServices;
	
	@Autowired
	private PermissionServices permissionServices;
	
	@Autowired
	private RoleServices roleServices;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//授权管理
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//这里等于从seesion里获取subiec对象
		Subject subject = SecurityUtils.getSubject();
		
		User user = (User) subject.getPrincipal();
		
		List<Role>  roles = roleServices.findByUsername(user);
		for (Role role : roles) {
			authorizationInfo.addRole(role.getKeyword());
		}
		
		List<Permission> permissions = permissionServices.findByUsername(user);
		for (Permission permission : permissions) {
			authorizationInfo.addStringPermission(permission.getKeyword());
		}
		
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		//认证管理
		UsernamePasswordToken token = (UsernamePasswordToken) arg0; 
		
		User user = userServices.findByUsername(token.getUsername());
		
		if (user==null) {
			return null;
		}else{
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
		
	}

}
